package script

import (
	"controllers"
	"github.com/astaxie/beego"
	"models"
	"encoding/json"
	"library/components"
	"github.com/astaxie/beego/orm"
	"strconv"
)

type ScriptExecController struct {
	controllers.BaseRouter
}

func (c *ScriptExecController) ExecTask () {
	//新建任务入库
	if c.User == nil  {
		c.SetJson(2, nil, "not login")
		return
	}
	beego.Info(string(c.Ctx.Input.RequestBody))
	var task models.GjScriptTask
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &task)
	if err != nil {
		c.SetJson(1, nil, "数据获取异常"+err.Error())
		return
	}
	task.Operator = c.User.UserName

	_,err = models.AddGjScriptTask(&task)
	if err != nil {
		c.SetJson(1, nil, "脚本任务录入数据库失败")
		return
	}

	//异步执行
	go func(){
		s := components.ScriptBaseComponents{}
		s.SetScriptTask(&task)
		s.RunRemoteCommand(components.GetExecCommand(task.ScriptContent),components.GetHosts(task.Hosts))

		InsertOption(1,task.Id,task.ScriptName,c.User.UserName)
	}()

	c.SetJson(200, task.Id, "开始执行脚本")
	return
}

func (c *ScriptExecController) ExecTest () {
	var task models.GjScriptTask
	task.Hosts="192.168.148.138"
	task.ScriptName = "测试脚本"
	task.Type = 0
	task.ScriptContent = "ping www.baidu.com"
	task.Timeout = 10
	task.ReleaseUser = "root"
	task.Operator = "dian"
	_,err := models.AddGjScriptTask(&task)
	if err != nil {
		c.SetJson(1, nil, "脚本任务录入数据库失败")
		return
	}

	//异步执行
	go func(){
		s := components.ScriptBaseComponents{}
		s.SetScriptTask(&task)
		s.RunRemoteCommand(components.GetExecCommand(task.ScriptContent),components.GetHosts(task.Hosts))
	}()

	c.SetJson(200, task.Id, "开始执行脚本")
	return
}


func InsertOption(types int,task_id int,content string,operator string) error {
	o := orm.NewOrm()
	sqlString := "insert into gj_history(type,task_id,content,operator) values(" + strconv.Itoa(types) + "," + strconv.Itoa(task_id) + ",'" + "script " + content + "','" + operator + "')"
	beego.Info(sqlString)
	_,err := o.Raw(sqlString).Exec()
	if err !=nil {
		return err
	}
	return nil
}